package com.cskaoyan.market.controller;


import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/wx/storage/fetch/*")
public class StorageFetchController extends HttpServlet {

    private String uploadBasePath;
    @Override
    public void init() throws ServletException {
        uploadBasePath =(String) getServletContext().getAttribute("upload");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String key = req.getRequestURI().replace(req.getContextPath() + "/wx/storage/fetch/", "");
        File file = new File(uploadBasePath + key);
        if (file.exists()&&file.isFile()){
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream();
            byte[] bytes = new byte[1024];
            int len =0;
            while((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
        }

    }
}
